package com.jiangnanxiaoguan.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiangnanxiaoguan.common.Result;
import com.jiangnanxiaoguan.entity.Employee;
import com.jiangnanxiaoguan.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 员工信息 前端控制器
 * </p>
 *
 * @author 不愿透露姓名的狂热者
 * @since 2022-09-11
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    // 前端请求写了二级路径，咱也得写上，不然找不着。（Restful本身可以不需要，但一个controller不可能就一个Post请求）
    @PostMapping("/login")
    public Result<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Employee::getId, Employee::getName,
                Employee::getUsername, Employee::getPassword,
                Employee::getPhone, Employee::getStatus);
        queryWrapper.eq(employee.getUsername() != null,
                Employee::getUsername, employee.getUsername());
        // 先查询基本的用户信息（登录功能会使用到账号名、账号密码、账号状态）。
        Employee emp = employeeService.getOne(queryWrapper);
        log.info("获取到用户对象：" + emp.toString());
        if (emp == null)
            return Result.error("用户不存在。");

        // 比较密码。
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if (!emp.getPassword().equals(password))
            return Result.error("密码错误。");

        // 账号是否已经禁用。
        if (emp.getStatus() == 0)
            return Result.error("该账号已被禁用。");

        request.getSession().setAttribute("employee", emp.getId());
        return Result.success(emp);
    }

    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
//        request.getSession().invalidate();  // 全部清除
        return Result.success("退出登录成功");
    }

    @PostMapping
    public Result<String> save(@RequestBody Employee employee, HttpServletRequest request) {
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        Long id = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(id);
//        employee.setUpdateUser(id);
        boolean save = employeeService.save(employee);
        return save ? Result.success("添加成功") : Result.error("添加失败");
    }

    @GetMapping("/page")
    public Result<IPage<Employee>> page(@RequestParam("page") Integer currentPage, Integer pageSize, String name) {
        log.info("[员工管理分页查询] - 查询页码：{}, 查询条数：{}, 查询条件：{}", currentPage, pageSize, name);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null && !"".equals(name), Employee::getName, name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        IPage<Employee> page = new Page<>(currentPage, pageSize);
        employeeService.page(page, queryWrapper);
//        System.out.println("当前页：" +  page.getCurrent());
//        System.out.println("每页大小：" + page.getSize());
//        System.out.println("总条数：" + page.getTotal());
//        System.out.println("总页数：" + page.getPages());
//        System.out.println("数据：" + page.getRecords());
        return Result.success(page);
    }

    @PutMapping
    public Result<String> update(@RequestBody Employee employee, HttpSession session) {
        log.info("id = {}, status = {}", employee.getId(), employee.getStatus());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser((Long) session.getAttribute("employee"));
        employeeService.updateById(employee);
        return Result.success("修改成功");
    }

    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (employee != null)
            return Result.success(employee);
        return Result.error("该用户不存在。");
    }
}

